package mysql

import (
	"Bluebell/dao/redis"
	"Bluebell/models"
	"strconv"
)

func CreatePost(p *models.Post) error {
	err := DB.Create(p).Error
	if err != nil {
		return err
	}
	err = redis.CreatePost(int64(p.PostID), p.CommunityID)
	return err
}

func GetPost(id int64) (post *models.Post, err error) {
	post = new(models.Post)
	if err = DB.Debug().Where("post_id=?", id).First(post).Error; err != nil {
		return nil, err
	}
	return post, err
}

func GetPostList(page, size int64) (post []*models.Post, err error) {
	post = make([]*models.Post, 0, 2)
	if err := DB.Limit(size).Offset((page - 1) * size).Find(&post).Error; err != nil {
		return nil, err
	}
	return post, err
}

//根据列表查询
func GetPostListByIDs(ids []string) (posts []*models.Post, err error) {
	res := make([]int64, len(ids))
	for index, val := range ids {
		res[index], _ = strconv.ParseInt(val, 10, 64)
	}
	//err = DB.Table("post").Where("post_id IN ?", res).Find(posts).Error
	for i := 0; i < len(res); i++ {
		post := new(models.Post)
		DB.Debug().Where("post_id=?", res[i]).First(post)
		posts = append(posts, post)
	}
	if err != nil {
		return nil, err
	}
	return posts, err
}
